const mongoose = require('mongoose');
const Counter = require('./counter');
const dayjs = require('dayjs');
const { Schema } = mongoose

const ArticleSchema = new Schema({
  article_id: {
    type: Number,
    unique: true,
    description: '文章id'
  },
  title: {
    type: String,
    unique: true,
    required: true,
    description: '标题'
  },
  content: {
    type: String,
    required: true,
    description: '内容'
  },
  tags: {
    type: Array,
    default: [],
    description: '标签'
  },
  sort_order: {
    type: Number,
    default: 0,
    description: '排序号，值越小越靠前'
  },
  status: {
    type: Number,
    default: 0,
    description: '状态，0:未发布 1:已发布'
  },
  category_id: {
    type: Array,
    required: true,
    description: '分类id'
  },
  view_count: {
    type: Number,
    default: 0,
    description: '浏览量'
  },
  created_by: {
    type: Number,
    default: null,
    description: '创建者id'
  },
  updated_by: {
    type: Number,
    default: null,
    description: '最后更新者id'
  },
  created_at: {
    type: String,
    default: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    description: '创建时间'
  },
  updated_at: {
    type: String,
    default: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    description: '最后更新时间'
  }
})

ArticleSchema.pre('save', async function(next, ctx) {
  if(this.isNew) {
    try {
      const counter = await Counter.findByIdAndUpdate(
        { _id: 'article_id' },
        { $inc: { seq: 1 } },
        { new: true, upsert: true }
      );
      this.article_id = counter.seq;
      next();
    } catch (error) {
      next(error);
    }
  } else {
    next();
  }
});

ArticleSchema.pre('updateOne', async function(next) {
  this.set({ updated_at: dayjs().format('YYYY-MM-DD HH:mm:ss') });
  next();
});

const articleModel = mongoose.model('article', ArticleSchema, 'article')

module.exports = articleModel